package com._54programer.demo.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * @author SN
 * @date Created by on 2019/11/29
 * @description
 * SimpleChannelInboundHandler是ChannelInboundHandlerAdapter的子类
 * 客户端和服务端通讯的数据被封装成HttpObject
 */
public class MyHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    /**
     * 读取数据
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        //1.判断是不是http请求
        if(msg instanceof HttpRequest){
            HttpRequest httpRequest = (HttpRequest)msg;
            //获取uri
            URI uri = new URI(httpRequest.uri());
            if("/favicon.ico".equals(uri.getPath())){
                System.out.println("忽略favicon.ico请求");
                return;
            }
            System.out.println("客户端地址："+ctx.channel().remoteAddress());
            //回复消息给客户端
            ByteBuf content = Unpooled.copiedBuffer("Hello Client", CharsetUtil.UTF_8);
            //构造一个HttpResponse
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
            //返回信息
            ctx.writeAndFlush(response);
        }
    }
}
